package com.hj.base;


import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.hj.base.impl.IBaseImpl;
import com.hj.base.impl.IBaseView;
import com.hj.base.impl.IntentCallBackInterface;
import com.hj.controller.ControlObserver;
import com.hj.controller.Controller;
import com.hj.controller.ControllerParamBean;
import com.hj.controller.ObserverCallback;
import com.hj.easypremissions.EasyPermissions;
import com.hj.easypremissions.helper.PermissionHelper;
import com.hj.statusbar.StatusBarUtil;
import com.hj.util.AppManager;
import com.hj.util.TUtil;

import java.util.Arrays;
import java.util.List;

/**
 * @function 作为Activity的基类，可以是MVP模式（出入具体的Presenter和Model替换泛型），也可以是普通模式。
 * <p>Presenter和Model通过泛型参数反射获取实例</p>
 * <p>{@goto onInitIntent(intent)}处理onNewIntent和onCreate中的intent</p>
 * <p>startActivityForResult通过IntentCallBackInterface回调直接处理回调结果</p>
 */

public abstract class BaseActivity<P extends BasePresenter, M extends BaseModel> extends AppCompatActivity implements IBaseView, IBaseImpl, EasyPermissions.PermissionCallbacks, View.OnClickListener {
    protected final String TAG = this.getClass().getSimpleName();
    public final int REQUEST_CODE = 10000;
    public final int STORAGE_CODE = 131;
    public final String[] STORAGE_PERMISSIONS = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};

    public final int CAMERA_CODE = 132;
    public final String[] CAMERA_PERMISSIONS = new String[]{Manifest.permission.CAMERA};

    public final int BLUETOOTH_CODE = 133;
    public final String[] BLUE_PERMISSIONS = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};

    private Dialog dialog;
    private ProgressDialog progressDialog;
    protected Intent intent;
    protected P mPresenter;
    protected M mModel;
    private int requestCode;
    private IntentCallBackInterface intentCallBack;
    private EasyPermissions.Callback callbacks;
    private ControlObserver observer = new ControlObserver() {
        @Override
        public void execute(Activity activity, String command, ControllerParamBean params, ObserverCallback callback) {
            BaseActivity.this.noticeReceiver(activity, command, params, callback);
        }
    };

    /**
     * 接收指令
     *
     * @param activity
     * @param command
     * @param params
     * @param callback
     */
    public void noticeReceiver(Activity activity, String command, ControllerParamBean params, ObserverCallback callback) {

    }

    /**
     * 处理实例化intent中的参数
     *
     * @param intent
     */
    protected void onInitIntent(Intent intent) {

    }

    /**
     * 懒加载
     */
    protected void onLazyLoad() {

    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "### onCreate ###");
        //注册消息推送
        Controller.registerObserver(this.observer);
        //通过参数反射获取Presenter和Model实例
        mPresenter = TUtil.getT(this, 0);
        mModel = TUtil.getT(this, 1);
        if (mPresenter != null)
            mPresenter.attachVM(this, mModel);

        //window参数设置（全屏，截屏权限等）
        setWindowParams();

        //设置布局视图
        setContentView(setContentViewId());

        setStatusBar();

        AppManager.getAppManager().addActivity(this);

        //获取intent
        this.intent = getIntent();

        //初始化控件
        initView();

        //处理intent中的参数
        onInitIntent(this.intent);

        //初始化数据
        initData();

        //初始化监听事件
        initListener();

//        memoryLog();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onLazyLoad();
            }
        }, 300);
    }

    @Override
    public void setWindowParams() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
//            View decorView = getWindow().getDecorView();
//            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
//            decorView.setSystemUiVisibility(option);
//            getWindow().setStatusBarColor(Color.TRANSPARENT);
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
//            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
//            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
//        }
    }

    public void setStatusBar() {
        StatusBarUtil.setColor(this, Color.WHITE, 0);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        this.intent = intent;
        //重新处理intent中的参数
        onInitIntent(this.intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppManager.getAppManager().log();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dimissDialog();
        hideLoading();
        if (mPresenter != null)
            mPresenter.detachView();
        this.mPresenter = null;
        this.mModel = null;
        this.intent = null;
        this.intentCallBack = null;
        Controller.unregisterObserver(this.observer);
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void showDialog(Dialog dialog) {
        if (this.dialog != null)
            this.dialog.dismiss();
        this.dialog = dialog;
        this.dialog.show();
    }

    @Override
    public void dimissDialog() {
        if (this.dialog != null)
            this.dialog.dismiss();
        this.dialog = null;
    }

    @Override
    public void showLoading() {
        if (progressDialog == null)
            progressDialog = new ProgressDialog(this);
        progressDialog.show();
    }

    @Override
    public void hideLoading() {
        if (progressDialog != null)
            progressDialog.dismiss();
        this.progressDialog = null;
    }

    @Override
    public Context mContext() {
        return this;
    }

    @Override
    public Activity mActivity() {
        return this;
    }

    public void startActivity(Class cls) {
        startActivity(new Intent(this, cls));
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        this.requestCode = requestCode;
        this.intentCallBack = null;
        super.startActivityForResult(intent, requestCode);
    }

    public void startActivityForResult(Intent intent, int requestCode, IntentCallBackInterface intentCallBack) {
        startActivityForResult(intent, requestCode);
        this.intentCallBack = intentCallBack;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "requestCode:" + requestCode + "; resultCode:" + resultCode);
        if (requestCode == this.requestCode) {
            if (intentCallBack != null) {
                if (resultCode == RESULT_OK) {
                    intentCallBack.onResultOK(data);
                } else if (resultCode == RESULT_CANCELED) {
                    intentCallBack.onResultCanceled(data);
                } else if (resultCode == RESULT_FIRST_USER) {
                    intentCallBack.onResultFirstUser(data);
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public int getRequestCode() {
        return requestCode;
    }

    public IntentCallBackInterface getIntentCallBack() {
        return intentCallBack;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    public void hasStoragePermissions(EasyPermissions.Callback callbacks) {
        requestPermission(callbacks, STORAGE_CODE, STORAGE_PERMISSIONS);
    }

    public void hasCameraPermissions(EasyPermissions.Callback callbacks) {
        requestPermission(callbacks, CAMERA_CODE, CAMERA_PERMISSIONS);
    }

    public void hasBluePermissions(EasyPermissions.Callback callbacks) {
        requestPermission(callbacks, BLUETOOTH_CODE, BLUE_PERMISSIONS);
    }

    public void requestPermission(EasyPermissions.Callback callbacks, int requestCode, @NonNull String... permissions) {
        this.callbacks = null;
        if (EasyPermissions.hasPermissions(this, permissions)) {
            if (callbacks != null) {
                callbacks.onGranted(requestCode, Arrays.asList(permissions));
            }
        } else {
            this.callbacks = callbacks;
            PermissionHelper.newInstance(this).directRequestPermissions(requestCode, permissions);
        }
    }

    public void requestPermission(EasyPermissions.Callback callbacks, @NonNull String... permissions) {
        requestPermission(callbacks, REQUEST_CODE, permissions);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (callbacks != null) {
            callbacks.onGranted(requestCode, perms);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (callbacks != null) {
            callbacks.onDenied(requestCode, perms);
        }
    }

    public void memoryLog() {
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        //最大分配内存
//        int memory = activityManager.getMemoryClass();
//        System.out.println("memory: " + memory);
        //最大分配内存获取方法2
        float maxMemory = (float) (Runtime.getRuntime().maxMemory() * 1.0 / (1024 * 1024));
        //当前分配的总内存
        float totalMemory = (float) (Runtime.getRuntime().totalMemory() * 1.0 / (1024 * 1024));
        //剩余内存
        float freeMemory = (float) (Runtime.getRuntime().freeMemory() * 1.0 / (1024 * 1024));
        System.out.println("最大分配内存: " + maxMemory);
        System.out.println("当前分配的总内存: " + totalMemory);
        System.out.println("剩余内存: " + freeMemory);
    }

    public void hideSoftInput() {
        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        im.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}
